package cn.com.nes.site.service.workOrder.impl;

import cn.com.nes.common.em.DateEnum;
import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.mybatis.callcenter.entity.WorkOrderInfo;
import cn.com.nes.mybatis.callcenter.entity.WorkOrderRecord;
import cn.com.nes.mybatis.callcenter.mapper.WorkOrderRecordMapper;
import cn.com.nes.site.entity.em.DeleteEnum;
import cn.com.nes.site.entity.em.WorkOrderStautsEnum;
import cn.com.nes.site.service.workOrder.CallWorkOrderInfoService;
import cn.com.nes.site.service.workOrder.WorkOrderRecordService;
import cn.com.nes.site.service.workOrder.dto.callCenter.WorkOrderRecordListDto;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WorkOrderRecordServiceImpl extends ServiceImpl<WorkOrderRecordMapper, WorkOrderRecord> implements WorkOrderRecordService {
    @Resource
    private WorkOrderRecordMapper workOrderRecordMapper;
    @Resource
    private CallWorkOrderInfoService callWorkOrderInfoService;

    //新增工单记录
    @Override
    public void saveWorkOrderRecord(long timeMillis, Long workOrderId, Integer status, String desc, BigDecimal longitude, BigDecimal latitude, Long maintainId, Long userId) {
        WorkOrderRecord workOrderRecord = new WorkOrderRecord();
        workOrderRecord.setIsDelete(Integer.valueOf(DeleteEnum._0.getKey()));
        workOrderRecord.setGmtCreate(timeMillis);
        workOrderRecord.setGmtModified(timeMillis);
        workOrderRecord.setWorkOrderId(workOrderId);
        workOrderRecord.setStatus(status);
        workOrderRecord.setDesc(desc);
        workOrderRecord.setLongitude(longitude);
        workOrderRecord.setLatitude(latitude);
        workOrderRecord.setMaintainId(maintainId);
        workOrderRecord.setUserId(userId);
        workOrderRecordMapper.insert(workOrderRecord);
    }

    @Override
    public void saveWorkOrderRecord(WorkOrderRecord workOrderRecord) {
        workOrderRecordMapper.insert(workOrderRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWorkOrderRecord(List<WorkOrderRecord> workOrderRecordList) {
        if (CollectionUtil.isEmpty(workOrderRecordList)) {
            return;
        }
        boolean success = this.saveBatch(workOrderRecordList);
        if (!success) {
            throw new IllegalBusinessException("批量新增工单操作记录失败!");
        }
    }

    /**
     * 查看通用工单记录
     *
     * @param workOrderId
     * @return
     *//*
    @Override
    public List<WorkOrderRecordListDto> getPublicWorkOrderRecordList(Long workOrderId) {
        List<WorkOrderRecordListDto> workOrderRecordList = workOrderRecordMapper.getWorkOrderRecordList(workOrderId);
        List<WorkOrderRecordListDto> newList = new ArrayList<>();
        for (int i = 0; i < workOrderRecordList.size(); i++) {
            WorkOrderRecordListDto workOrderRecordListDto = workOrderRecordList.get(i);
            String desc;
            if (i > 0) {
                WorkOrderRecordListDto dto = workOrderRecordList.get(i - 1);
                desc = PublicWorkOrderStatusUtils.getWorkOrderStatusDesc(workOrderRecordListDto.getStatus(), dto.getStatus());
            } else {
                desc = PublicWorkOrderStatusUtils.getWorkOrderStatusDesc(workOrderRecordListDto.getStatus(), -1);
            }
            workOrderRecordListDto.setDesc(desc);
            newList.add(workOrderRecordListDto);
        }
        return newList;
    }*/

    @Override
    public List<WorkOrderRecordListDto> getWorkOrderRecordList(Long workOrderId) {
        ArrayList<Long> workOrderIdList = new ArrayList<>();
        updateWorkOrderInfo(workOrderId, workOrderIdList);
        List<WorkOrderRecordListDto> workOrderRecordList = workOrderRecordMapper.getWorkOrderRecordList(workOrderIdList);
        long createWorkOrder = 0L;
        long receipt = 0L;
        long punchClock = 0L;
        long finish = 0L;
        for (int i = workOrderRecordList.size() - 1; i >= 0; i--) {
            WorkOrderRecordListDto dto = workOrderRecordList.get(i);
            Integer status = dto.getStatus();
            String desc = dto.getDesc();
            if (status == 2 && desc.startsWith("创建工单")) {
                createWorkOrder = dto.getGmtCreate();
            } else if (status == 2 && desc.startsWith("维修人员已接单")) {
                receipt = dto.getGmtCreate();
                long diff = receipt - createWorkOrder;
                if (diff > 10 * DateEnum._1.getConvert()) {
                    dto.setTimeOutStatus(true);
                }
            } else if (status == 2 && desc.startsWith("维修人员已到达")) {
                punchClock = dto.getGmtCreate();
                long diff = punchClock - createWorkOrder;
                if (diff > 2 * DateEnum._2.getConvert()) {
                    dto.setTimeOutStatus(true);
                }
            } else if (status == 6 && desc.startsWith("故障描述:")) {
                finish = dto.getGmtCreate();
                long diff = finish - createWorkOrder;
                if (diff > 4 * DateEnum._2.getConvert()) {
                    dto.setTimeOutStatus(true);
                }
            }
        }
        return workOrderRecordList;
    }

    @Override
    public void updateWorkOrderRecord(Long workOrderId) {
        QueryWrapper<WorkOrderRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.eq("work_order_id", workOrderId);
        queryWrapper.eq("status", WorkOrderStautsEnum._8.getKey());
        queryWrapper.eq("effective_record", Boolean.TRUE);
        List<Long> workOrderRecordIdList = this.baseMapper.selectList(queryWrapper).stream().map(WorkOrderRecord::getId).collect(Collectors.toList());

        for (Long id : workOrderRecordIdList) {
            WorkOrderRecord workOrderRecord = new WorkOrderRecord();
            workOrderRecord.setId(id);
            workOrderRecord.setEffectiveRecord(Boolean.FALSE);
            this.baseMapper.updateById(workOrderRecord);
        }
    }

    public void updateWorkOrderInfo(Long id, ArrayList<Long> list) {
        if (ObjectUtil.isNotEmpty(id)) {
            list.add(id);
            WorkOrderInfo pWorkOrderInfo = callWorkOrderInfoService.getWorkOrderByPworkOrderId(id);
            if (pWorkOrderInfo != null) {

                updateWorkOrderInfo(pWorkOrderInfo.getId(), list);
            } else {
                updateWorkOrderInfo(null, list);
            }
        }

    }
}
